package org.example.mrrope.service;

import lombok.extern.slf4j.Slf4j;
import org.example.mrrope.utils.DingUtil;
import org.example.mrrope.utils.FormUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * CYQ
 * 制结&手工 工车间下发派工单
 */
@Service
@Slf4j
public class DoKnotWorkOrder {

    @Autowired
    private DingUtil dingUtil;

    public Integer getDoKnot(JSONObject upJsonA, String id, String userId) throws Exception {
        String s = null;
        //查询子表单是否有值
        if (upJsonA.has("tableField_lwed3a1x")) {
            JSONArray jsonArrTow = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lwed3a1x");
            JSONObject upJsonE = new JSONObject();
            //---------------------------成品信息---------------------------
            upJsonE.put("numberField_lugarhfl", upJsonA.has("numberField_lx41w1sv") ? upJsonA.get("numberField_lx41w1sv") : "");//订单总数
            List<String> list2 = new ArrayList<>();
            for (int i = 0; i < jsonArrTow.length(); i++) {
                JSONObject jsInBOM = jsonArrTow.getJSONObject(i);
                JSONObject upJsonB = new JSONObject(upJsonE.toString());
                String numberB = jsInBOM.getString("textField_lujgt592");
                //判断半成品是不是仅采购,仅采购结束循环
                if (jsInBOM.has("radioField_m4qllfwm")) {
                    if (jsInBOM.getString("radioField_m4qllfwm").equals("是")) {
                        continue;
                    }
                }
                //--------------------------------------------------------------------------------------------------
                //查询当前半成BOM里面的是否需要制结
                JSONObject searchFieldJson = new JSONObject();
                //查询半成BOM
                searchFieldJson.put("textField_lujgt576", numberB);
                String yiDaSearchReturnData_XSDD = dingUtil.yiDaSearchReturnData("FORM-916B5F5CEECE4FB5ADD382411F8DCFF9FSLS", searchFieldJson);//获取半成品
                JSONArray yiDaSearchReturnData_XSDDJsonArray = new JSONArray(yiDaSearchReturnData_XSDD);
                JSONObject xsddJSONObject = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getJSONObject("formData");
                String SOID = yiDaSearchReturnData_XSDDJsonArray.getJSONObject(0).getString("formInstanceId");
                //判断是否有制结
                int isZhiJieAndsgon = 0;
                String zhiJieAndsgon = "";
                if (xsddJSONObject.has("radioField_mac44oxm") ){
                    if (xsddJSONObject.get("radioField_mac44oxm").equals("否")){
                        isZhiJieAndsgon++;
                    }else {
                        zhiJieAndsgon=zhiJieAndsgon+"制结;";
                        upJsonB.put("textField_lzcam5ri", zhiJieAndsgon);//制结还是手工
                    }
                }else{
                    zhiJieAndsgon=zhiJieAndsgon+"制结;";
                    upJsonB.put("textField_lzcam5ri", zhiJieAndsgon);//制结还是手工
                }
                if ( xsddJSONObject.has("radioField_mcbctaby")){
                    if (xsddJSONObject.get("radioField_mcbctaby").equals("否")){
                        isZhiJieAndsgon++;
                    }else {
                        zhiJieAndsgon=zhiJieAndsgon+"手工;";
                        upJsonB.put("textField_lzcam5ri", zhiJieAndsgon);//制结还是手工
                    }
                }else {
                    zhiJieAndsgon=zhiJieAndsgon+"手工;";
                    upJsonB.put("textField_lzcam5ri", zhiJieAndsgon);//制结还是手工
                }
                if (isZhiJieAndsgon > 1){
                    continue;
                }
                //-----------------------------配件-----------------------------------------
                String typePeiJian = null;
                if (upJsonA.has("tableField_lvxe56yi")) {
                    JSONArray peiJianArray = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lvxe56yi");
                    ArrayList<JSONObject> listOnZhiJie = new ArrayList<>();
                    for (int j = 0; j < peiJianArray.length(); j++) {
                        JSONObject peiJianObject = peiJianArray.getJSONObject(j);
                        JSONObject ShouGon = new JSONObject();
                        String numberD = (String) peiJianObject.get("textField_lx07bljk");
                        if (!numberB.equals(numberD)) {
                            continue;
                        }
                        if (peiJianObject.has("radioField_lxsgdwtr")) {
                            typePeiJian = (String) peiJianObject.get("radioField_lxsgdwtr");
                            if (typePeiJian.equals("手工")) {
                                ShouGon.put("textField_lx07bljk", peiJianObject.has("textField_lx07bljk") ? peiJianObject.get("textField_lx07bljk") : "");//半成品B号
                                ShouGon.put("textField_lujgt59d", peiJianObject.has("textField_lujgt59d") ? peiJianObject.get("textField_lujgt59d") : "");//配件名称
                                ShouGon.put("textField_lujgt59f", peiJianObject.has("textField_lujgt59f") ? peiJianObject.get("textField_lujgt59f") : "");//配件编号
                                ShouGon.put("textField_lx3ck53r", peiJianObject.has("textField_lx3ck53r") ? peiJianObject.get("textField_lx3ck53r") : "");//规格描述
                                ShouGon.put("textField_lx2luc3t", peiJianObject.has("textField_lx2luc3t") ? peiJianObject.get("textField_lx2luc3t") : "");//是否打孔
                                ShouGon.put("textField_lx2luc3s", peiJianObject.has("textField_lx2luc3s") ? peiJianObject.get("textField_lx2luc3s") : "");//打孔规格
                                ShouGon.put("imageField_lwg902pf", peiJianObject.has("imageField_lwg902pf") ? peiJianObject.get("imageField_lwg902pf") : "");//例图
                                ShouGon.put("textField_lwee5prf", peiJianObject.has("textField_lwee5prf") ? peiJianObject.get("textField_lwee5prf") : "");//备注
                                ShouGon.put("numberField_lxwv7czp", peiJianObject.has("numberField_lxwv7czp") ? peiJianObject.get("numberField_lxwv7czp") : 0);//配件总领量数
                                ShouGon.put("numberField_m607x6hs", peiJianObject.has("numberField_m4hx46fs") ? peiJianObject.get("numberField_m4hx46fs") : 0);//配件总领量数
                                ShouGon.put("numberField_lxvgkgg8", peiJianObject.has("numberField_lxvgkgg8") ? peiJianObject.get("numberField_lxvgkgg8") : 0);//标准用量
                                ShouGon.put("radioField_lxsgdwtr", peiJianObject.has("radioField_lxsgdwtr") ? peiJianObject.get("radioField_lxsgdwtr") : "");//类型
                                listOnZhiJie.add(ShouGon);
                            }
                        }
                    }
                    log.info("配件-----------------------------------------------------------------" + listOnZhiJie);
                    upJsonB.put("tableField_lvxe56yi", listOnZhiJie);//配件
                }
                //------------------------------绳子----------------------------------------
                ArrayList<JSONObject> listTowShouGon = new ArrayList<>();
                JSONObject shengZiObject = null;
                if (upJsonA.has("tableField_lujgt57k")) {
                    JSONArray yanSeArray = dingUtil.getInnerTables(id, "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW", "tableField_lujgt57k");
                    for (int k = 0; k < yanSeArray.length(); k++) {
                        shengZiObject = yanSeArray.getJSONObject(k);
                        if (shengZiObject.has("textField_lx07bljm")) {
                            String numberC = (String) shengZiObject.get("textField_lx07bljm");
                            if (!numberB.equals(numberC)) {
                                continue;
                            }
                        }
                        JSONObject shengZiShouGon = new JSONObject();
                        shengZiShouGon.put("textField_lxwy3kxf", shengZiObject.has("textField_lujgt57l") ? shengZiObject.get("textField_lujgt57l") : "");//半成品绳子C号
                        shengZiShouGon.put("textField_lxd6qtml", shengZiObject.has("textField_lxd6qtml") ? shengZiObject.get("textField_lxd6qtml") : "");//绳子名称
                        shengZiShouGon.put("numberField_lujhx4e2", shengZiObject.has("numberField_lujhx4e2") ? shengZiObject.get("numberField_lujhx4e2") : "");//辅机重量
                        shengZiShouGon.put("textareaField_lxwy3kxh", shengZiObject.has("textareaField_lvxhxh0a") ? shengZiObject.get("textareaField_lvxhxh0a") : "");//花色挂法
                        shengZiShouGon.put("textField_m3fg7rs1", shengZiObject.has("textField_lxipl733") ? shengZiObject.get("textField_lxipl733") : "");//规格
                        shengZiShouGon.put("numberField_lxwy3kxg", shengZiObject.has("numberField_lujhx4e0") ? shengZiObject.get("numberField_lujhx4e0") : "");//绳子口径
                        shengZiShouGon.put("numberField_lxvgkgg4", shengZiObject.has("numberField_lz6dt0zh") ? shengZiObject.get("numberField_lz6dt0zh") : "");//标准用量
                        shengZiShouGon.put("numberField_lxwv7czn", shengZiObject.has("numberField_lxwv7czn") ? shengZiObject.get("numberField_lxwv7czn") : "");//绳子总领量数
                        shengZiShouGon.put("selectField_lxtpnbg4", shengZiObject.has("selectField_lxtpnbg4") ? shengZiObject.get("selectField_lxtpnbg4") : "");//绳子口径
                        shengZiShouGon.put("imageField_lz761vpx", shengZiObject.has("imageField_lxy4xj34") ? shengZiObject.get("imageField_lxy4xj34") : "");//绳子图片
                        shengZiShouGon.put("numberField_lzbfxx57", shengZiObject.has("numberField_lzaqcadd") ? shengZiObject.get("numberField_lzaqcadd") : "");//切绳重量
                        shengZiShouGon.put("numberField_lxwv7czn", shengZiObject.has("numberField_lxwv7czn") ? shengZiObject.get("numberField_lxwv7czn") : "");//总应发数量
                        shengZiShouGon.put("numberField_m607x6hr", shengZiObject.has("numberField_m5z1tmyq") ? shengZiObject.get("numberField_m5z1tmyq") : "");//实际总应发数量
                        listTowShouGon.add(shengZiShouGon);
                    }
                }
                upJsonB.put("tableField_lxwy3kxi", listTowShouGon);//绳子
                upJsonB.put("numberField_lugarhfl", jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.get("numberField_lxwv7czo") : 0);//生产总量
                upJsonB.put("numberField_m607x6hq", jsInBOM.has("numberField_m5z1tmyo") ? jsInBOM.get("numberField_m5z1tmyo") : 0);//实际生产总量
                upJsonB.put("numberField_m3hocs53", jsInBOM.has("numberField_lxvgkgg7") ? jsInBOM.get("numberField_lxvgkgg7") : 0);//标准用量、
                upJsonB.put("radioField_m42cd3fr", "正常");//派工单状态
                //搜索现有派工单
                JSONObject searchScheduleJson = new JSONObject();
                searchScheduleJson.put("textField_lyz6ump9", upJsonA.has("textField_lwt4u8ls") ? upJsonA.get("textField_lwt4u8ls") : "");//so号
                searchScheduleJson.put("textField_lugarhfd", numberB);//半成品号
                String yiDaSearchReturnData_Schedule = dingUtil.yiDaSearchReturnData("FORM-130978341E17408FB02F6B757F096B2FSOVO", searchScheduleJson);//获取缝纫派工单数据
                JSONArray yiDaSearchReturnData_ScheduleJsonArray = new JSONArray(yiDaSearchReturnData_Schedule);
                if (!yiDaSearchReturnData_ScheduleJsonArray.isEmpty()) {
                    String oid = yiDaSearchReturnData_ScheduleJsonArray.getJSONObject(0).getString("formInstanceId");
                    JSONObject zsObject = new JSONObject(dingUtil.getYidaById(oid));//原有派工单
                    Double todoAmount = jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.getDouble("numberField_lxwv7czo") : 0.0;//应有的待完成量
                    Double finishedAmount = zsObject.has("numberField_lzbzzy7k") ? zsObject.getDouble("numberField_lzbzzy7k") : 0.0;//已完成量
                    Double dispatchedAmount = zsObject.has("numberField_m3y33nue") ? zsObject.getDouble("numberField_m3y33nue") : 0.0;//已下发量
                    Double receivedAmount = zsObject.has("numberField_lzc19v9g") ? zsObject.getDouble("numberField_lzc19v9g") : 0.0;//已入库量
                    upJsonB.put("numberField_lzbzzy7l", todoAmount - finishedAmount);//上缴
                    upJsonB.put("numberField_m3y33nuf", todoAmount - dispatchedAmount);//未下发
                    upJsonB.put("numberField_lzc19v9h", todoAmount - receivedAmount);//未入库
                    log.info("更新 制结手工车间派工单开始");
                    log.info("更新oid:{}", oid);
                    log.info("更新数据:{}", upJsonB);
                    dingUtil.UpdateYiDa(oid, upJsonB);//更新生产计划
                    log.info("更新 制结手工车间派工单完成");
                } else {

                    //------------------------------ 生产计划里面的数据赋值------------------------------------------
                    upJsonB.put("textField_lx1mddjk", upJsonA.has("textField_lujgt578") ? upJsonA.get("textField_lujgt578") : "");//客户名称
                    upJsonB.put("radioField_m3iilehf", upJsonA.has("radioField_m3iilehf") ? upJsonA.get("radioField_m3iilehf") : "");//外加工
                    upJsonB.put("textField_m2u6ubhy", upJsonA.has("textField_m2e5ira7") ? upJsonA.get("textField_m2e5ira7") : "");//合同号
                    upJsonB.put("textField_lyz6ump9", upJsonA.has("textField_lwt4u8ls") ? upJsonA.get("textField_lwt4u8ls") : "");//SO号
                    upJsonB.put("textField_lugarhfe", upJsonA.has("textField_lujgt577") ? upJsonA.get("textField_lujgt577") : "");//客人货号
                    upJsonB.put("dateField_m3hht0jr", upJsonA.has("dateField_m2wwkxe1") ? upJsonA.get("dateField_m2wwkxe1") : "");//手工&制结计完成时间
                    upJsonB.put("radioField_mann5ewv", upJsonA.has("radioField_makqj7ph") ? upJsonA.get("radioField_makqj7ph") : "苍南");//工厂
//                    upJsonB.put("textField_lzcam5ri", "制结");//类型

                    //--------------------------------半成品BOM里面的数据赋值----------------------------------------------------------
                    upJsonB.put("textField_lugarhfx", jsInBOM.has("textareaField_m2ohpz46") ? jsInBOM.get("textareaField_m2ohpz46") : "");//规格/重量
                    upJsonB.put("textField_lxifktd1", jsInBOM.has("textField_lwbmqipz") ? jsInBOM.get("textField_lwbmqipz") : "");//名称
                    upJsonB.put("imageField_lugarhfm", jsInBOM.has("imageField_lwt5fomx") ? jsInBOM.get("imageField_lwt5fomx") : "");//图片
                    upJsonB.put("textareaField_m2bopkpp", jsInBOM.has("textField_lxk8d6fp") ? jsInBOM.get("textField_lxk8d6fp") : "");//注意点
                    upJsonB.put("textField_lugarhfd", numberB);//B号
                    upJsonB.put("textField_m0fhza4i", "KG");//单位

                    //--------------------关联半成品BOM----------------------
                    String fromUuid = "FORM-3A8D681A77094B6DAF95EBB52ABF301DGFLW";
                    // 通过调用FormUtils的getAssociationFormField方法，根据fromUuid、title和id获取关联表单字段的JSON数组
                    JSONArray jsonArrayOne = FormUtils.getAssociationFormField(fromUuid, upJsonA.getString("textField_lwt4u8ls"), id);
                    upJsonB.put("associationFormField_lwt4miug", jsonArrayOne);

                    upJsonB.put("numberField_lzbzzy7l", jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.get("numberField_lxwv7czo") : 0);//待转交/上缴
                    upJsonB.put("numberField_lzc19v9h", jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.get("numberField_lxwv7czo") : 0);//待入库
                    upJsonB.put("numberField_m3y33nuf", jsInBOM.has("numberField_lxwv7czo") ? jsInBOM.get("numberField_lxwv7czo") : 0);//待下发
                    upJsonB.put("numberField_lzc1jw04", jsInBOM.has("numberField_m4w3ia5c") ? jsInBOM.get("numberField_m4w3ia5c") : 0);//制结工价
                    upJsonB.put("numberField_m2a3jcin", jsInBOM.has("numberField_m4w3ia5d") ? jsInBOM.get("numberField_m4w3ia5d") : 0);//手工工价
                    upJsonB.put("numberField_lzc19v9g", 0);//已入库
                    upJsonB.put("numberField_lzbzzy7k", 0);//已转交/上缴
                    upJsonB.put("numberField_m3y33nue", 0);//已下发

                    s = dingUtil.startInstance(upJsonB, userId, "FORM-130978341E17408FB02F6B757F096B2FSOVO");
                    log.info("YIDA-startInstance 制结手工车间派工单生成流程完成" + s);
                }
            list2.add(numberB);
            }

            //查找现有的派工单，进行循环，多余的派工单删除
            //根据SO号搜索
            JSONObject paiGonJson = new JSONObject();
            paiGonJson.put("textField_lyz6ump9", upJsonA.has("textField_lwt4u8ls") ? upJsonA.get("textField_lwt4u8ls") : "");//so号
            String yiDaPaiGonString = dingUtil.yiDaSearchReturnData("FORM-130978341E17408FB02F6B757F096B2FSOVO", paiGonJson);//获取派工单数据
            JSONArray yiDaPaiGonJsonArray = new JSONArray(yiDaPaiGonString);
            HashMap<String, String> newMap = new HashMap<>();
            List<String> list1 = new ArrayList<>();
            //把B号存在容器里面
            for (int i = 0; i < yiDaPaiGonJsonArray.length(); i++){
                String oid = yiDaPaiGonJsonArray.getJSONObject(i).getString("formInstanceId");
                JSONObject pgdObject = new JSONObject(dingUtil.getYidaById(oid));//原有派工单
                if (pgdObject.has("textField_lugarhfd")){
                    list1.add(pgdObject.getString("textField_lugarhfd"));
                    newMap.put(pgdObject.getString("textField_lugarhfd"),oid);
                }
            }
            // 找出派工单中有但生产计划中没有的元素
            // 派工单 减 生产计划 多出来的就是没用的派工单
            list1.removeAll(list2);
            if (list1.size() > 0){
                for (String numberB : list1) {
                    //删除多余的派工单
                    if (newMap.containsKey(numberB)){
                        JSONObject object = new JSONObject();
                        object.put("radioField_m42cd3fr", "暂停");
                        dingUtil.UpdateYiDa(newMap.get(numberB), object);
//                        dingUtil.delete(newMap.get(numberB));
                    }
                }
            }
        }
        return s == null ? 1 : 0;
    }

//    public static List<String> getDifference(JSONArray array1, JSONArray array2) {
//        List<JSONObject> diffList = new ArrayList<>();
//        for (int i = 0; i < array1.length(); i++) {
//            String obj1 = array1.getString(i);
//            boolean found = false;
//            for (int j = 0; j < array2.length(); j++) {
//                JSONObject obj2 = array2.getJSONObject(j);
//                if (obj1.toString().equals(obj2.toString())) {
//                    found = true;
//                    break;
//                }
//            }
//            if (!found) {
//                diffList.add(obj1);
//            }
//        }
//        return diffList;
//    }
}
